<template>
  <div class="equipment-operation">
    <!-- 页面标题和统计 -->
    <div class="header">
      <h2>设备归还管理</h2>
      <div class="stats">
        <el-tag type="info" class="stat-tag">
          总设备: {{ totalEquipment }}
        </el-tag>
        <el-tag type="success" class="stat-tag">
          可用设备: {{ availableEquipment }}
        </el-tag>
        <el-tag type="warning" class="stat-tag">
          我的借用: {{ myBorrowedEquipment }}
        </el-tag>
      </div>
    </div>

    <!-- 操作选项卡 -->
    <el-tabs v-model="activeTab" class="operation-tabs">
      <!-- 设备归还 -->
      <el-tab-pane label="设备归还" name="return">
        <div class="tab-content">
          <!-- 我的借用记录 -->
          <el-table 
            :data="myBorrowedList" 
            style="width: 100%"
            v-loading="borrowedLoading"
          >
            <el-table-column prop="id" label="设备ID" width="80" />
            <el-table-column prop="name" label="设备名称" width="200" />
            <el-table-column prop="description" label="设备描述" min-width="200" />
            <el-table-column prop="borrowTime" label="借用时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.borrowTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag type="warning">使用中</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="{ row }">
                <el-button
                  type="success"
                  size="small"
                  @click="handleReturn(row)"
                >
                  归还
                </el-button>
                <el-button
                  type="warning"
                  size="small"
                  @click="handleRepairRequest(row)"
                >
                  申请维修
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-if="myBorrowedList.length === 0" description="暂无借用记录" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 维修申请对话框 -->
    <el-dialog
      v-model="repairDialogVisible"
      title="设备维修申请"
      width="500px"
    >
      <el-form 
        :model="repairForm" 
        :rules="repairRules"
        ref="repairFormRef"
        label-width="100px"
      >
        <el-form-item label="设备名称">
          <el-input v-model="selectedEquipment.name" disabled />
        </el-form-item>
        <el-form-item label="故障描述" prop="faultDescription">
          <el-input
            v-model="repairForm.faultDescription"
            type="textarea"
            :rows="4"
            placeholder="请详细描述设备故障情况"
          />
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgency">
          <el-radio-group v-model="repairForm.urgency">
            <el-radio label="低">一般故障</el-radio>
            <el-radio label="中">影响使用</el-radio>
            <el-radio label="高">紧急维修</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="repairDialogVisible = false">取消</el-button>
          <el-button 
            type="warning" 
            @click="confirmRepairRequest"
            :loading="repairSubmitting"
          >
            提交维修申请
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 响应式数据
const activeTab = ref('return')
const borrowedLoading = ref(false)
const repairDialogVisible = ref(false)
const repairSubmitting = ref(false)

// 表单引用
const repairFormRef = ref()

// 数据列表
const equipmentList = ref([])
const myBorrowedList = ref([])
const selectedEquipment = ref({})

// 统计数据
const totalEquipment = computed(() => equipmentList.value.length)
const availableEquipment = computed(() => 
  equipmentList.value.filter(item => item.status === '空闲').length
)
const myBorrowedEquipment = computed(() => myBorrowedList.value.length)

// 维修表单
const repairForm = reactive({
  faultDescription: '',
  urgency: '中'
})

const repairRules = reactive({
  faultDescription: [
    { required: true, message: '请描述故障情况', trigger: 'blur' },
    { min: 10, max: 500, message: '故障描述应在10-500个字符之间', trigger: 'blur' }
  ],
  urgency: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ]
})

// 获取设备列表
const getEquipmentList = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/v1/admin/equStatus')
    if (response.data.code === 200) {
      equipmentList.value = response.data.data
    } else {
      ElMessage.error('获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('网络请求失败')
  }
}

// 获取我的借用记录
const getMyBorrowedList = async () => {
  borrowedLoading.value = true
  try {
    // 获取所有设备
    const response = await axios.get('http://localhost:8080/api/v1/admin/equStatus')
    if (response.data.code === 200) {
      // 只保留状态为“使用中”的设备
      myBorrowedList.value = response.data.data
        .filter(item => item.status === '使用中')
        .map(item => ({
          id: item.id,
          name: item.name,
          description: item.description,
          borrowTime: item.update_time // 这里假设 update_time 为借用时间
        }))
    } else {
      ElMessage.error('获取借用记录失败')
    }
  } catch (error) {
    console.error('获取借用记录失败:', error)
    ElMessage.error('获取借用记录失败')
  } finally {
    borrowedLoading.value = false
  }
}

// 处理设备归还
const handleReturn = async (equipment) => {
  try {
    await ElMessageBox.confirm(
      `确定要归还设备 "${equipment.name}" 吗？`,
      '归还确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const userId = localStorage.getItem('userId')
    const response = await axios.post('http://localhost:8080/api/v1/stu/return', {
      equipmentId: equipment.id,
      userId: parseInt(userId)
    })
    
    if (response.data.code === 200) {
      ElMessage.success('设备归还成功')
      getMyBorrowedList() // 刷新借用记录
      getEquipmentList() // 刷新设备列表
    } else {
      ElMessage.error(response.data.message || '归还失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归还失败:', error)
      ElMessage.error('网络请求失败')
    }
  }
}

// 处理维修申请
const handleRepairRequest = (equipment) => {
  selectedEquipment.value = equipment
  repairDialogVisible.value = true
  // 重置表单
  repairForm.faultDescription = ''
  repairForm.urgency = '中'
}

// 确认维修申请
const confirmRepairRequest = async () => {
  if (!repairFormRef.value) return
  
  await repairFormRef.value.validate(async (valid) => {
    if (valid) {
      repairSubmitting.value = true
      
      try {
        const userId = localStorage.getItem('userId')
        
        // 组合故障描述和紧急程度
        const combinedRemark = `【紧急程度:${repairForm.urgency}】${repairForm.faultDescription}`
        
        // 使用新的维修申请接口
        const response = await axios.post('http://localhost:8080/api/v1/stu/repair', {
          equipmentId: selectedEquipment.value.id,
          userId: parseInt(userId),
          remark: combinedRemark // 将组合后的信息作为备注提交
        })
        
        if (response.data.code === 200) {
          ElMessage.success('维修申请提交成功')
          repairDialogVisible.value = false
          
          // 刷新相关数据
          getMyBorrowedList() // 刷新借用记录
          getEquipmentList() // 刷新设备列表，设备状态可能变为维修中
        } else {
          ElMessage.error(response.data.message || '维修申请失败')
        }
      } catch (error) {
        console.error('维修申请失败:', error)
        
        if (error.response) {
          ElMessage.error(error.response.data.message || '维修申请失败')
        } else if (error.request) {
          ElMessage.error('网络连接失败，请检查网络')
        } else {
          ElMessage.error('维修申请失败，请稍后重试')
        }
      } finally {
        repairSubmitting.value = false
      }
    } else {
      // 表单验证失败
      ElMessage.warning('请完善维修申请信息')
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getEquipmentList()
  getMyBorrowedList()
})
</script>

<style scoped>
.equipment-operation {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.stats {
  display: flex;
  gap: 10px;
}

.stat-tag {
  padding: 8px 16px;
}

.operation-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .stats {
    flex-wrap: wrap;
  }
}
</style>